﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.UI;
using UTSDAL.LINQSQL.Model;
using UTSDAL.LINQSQL.DAO;


namespace UTS.Controls
{
    [
        DefaultProperty("Text"),
        ToolboxData("<{0}:SemesterDropDownList runat=\"server\"> </{0}:SemesterDropDownList>")
    ]
    public class SemesterDropDownList : System.Web.UI.WebControls.DropDownList
    {
        private SemesterDAO semesterDAO = new SemesterDAO();


        private void init()
        {

            this.DataSource = semesterDAO.selectAll();
            this.DataBind();
            DropDownUtils.addDefaultLabel(this, "Select a Semester");
            this.DataTextField = "SemesterName";
            this.DataValueField = "SemesterId";
        }

        // this method bypasses non post back requests by ajax
        public void reload()
        {
            init();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                init();
            }
            
        }


        private Semester semester;

        public Semester Semester
        {
            get {
                if (StringUtils.isValidGuid(this.SelectedValue.ToString()))
                {

                    semester = semesterDAO.findById(new Guid(this.SelectedValue.ToString()));
                }
                else
                {
                    semester = null;
                }
                return semester; 
            }
            set 
            { 
                semester = value;
                if (semester != null)
                {
                    this.SelectedValue = semester.SemesterId.ToString();
                }
            }
        }

    }
}